import { nextTick } from 'vue'
import { getAppPages, getSubPackagesPages} from "@/utils/pages"

// 预加载所有 app 与 addon 的语言包，确保 APP 端能正确打包
const appLocaleModules: Record<string, any> = import.meta.glob('../app/locale/*/*.json', { eager: true })
const addonLocaleModules: Record<string, any> = import.meta.glob('../addon/**/locale/*/*.json', { eager: true })

const resolveLocaleModule = (route: string, locale: string, file: string): any => {
    // 生成可能的匹配路径键
    const appKey = `../app/locale/${locale}/${file}.json`
    const addonKey = `../addon/${route}/locale/${locale}/${file}.json`
    // 优先匹配 app，再匹配 addon
    if (appLocaleModules[appKey]) return appLocaleModules[appKey]
    if (addonLocaleModules[addonKey]) return addonLocaleModules[addonKey]
    return null
}

class Language {
    private i18n: any
    private loadLocale: Array<string> = [] //已加载的语言

    public path = ''

    constructor(i18n: any) {
        this.i18n = i18n
    }

    /**
     *
     * @param locale 设置语言
     */
    public setI18nLanguage(locale: string, path: string = '') {
        if (this.i18n.global.locale == locale) return
        this.i18n.global.locale = locale
        path && (this.path = path)
        uni.setLocale(locale)
    }

    public loadAllLocaleMessages(app: string, locale: string) {
        const pages = app == 'app' ? getAppPages() : getSubPackagesPages()
        pages.forEach((path: string) => {
            this.loadLocaleMessages(path, locale)
        })
    }

    /**
     * 加载语言包
     * @param path
     * @param locale
     * @returns
     */
    public async loadLocaleMessages(path: string, locale: string) {
        try {
            const { route, file, fileKey } = this.getFileKey(path)

            // 是否已加载
            if (this.loadLocale.includes(`${fileKey}.${locale}`)) {
                this.setI18nLanguage(locale, file)
                return nextTick()
            }
            
            // 使用 import.meta.glob 的静态模块表，统一在各端加载
            const mod: any = resolveLocaleModule(route, locale, file)
            if (mod && (mod.default || typeof mod === 'object')) {
                const messages: any = mod.default || mod
                let data: Record<string, string> = {}
                Object.keys(messages).forEach(key => {
                    data[`${fileKey}.${key}`] = messages[key]
                })

                this.i18n.global.mergeLocaleMessage(locale, data)
                this.setI18nLanguage(locale, file)

                this.loadLocale.push(`${fileKey}.${locale}`)
            }

            return nextTick()
        } catch (e) {
            this.setI18nLanguage(locale)
            return nextTick()
        }
    }

    // 统一由 import.meta.glob 的静态映射处理

    public getFileKey = (path: string) => {
        const pathArr = path.split('/')
        let route = pathArr[1] == 'app' ? pathArr[1] : pathArr[2];
        let file = path == '/' ? 'pages.index.index' : '';
        // #ifndef APP-PLUS
        file = path.replace('/', '')?.replaceAll('/', '.')
        // #endif
        // #ifdef APP-PLUS
        file = path.split('/').filter(Boolean).join('.')
        // #endif
        // 如果是系统页面，则移除"app."
        let fileKey = ''
        if (route == 'app') {
            fileKey = file?.replace('app.', '')
            file = file?.replace('app.', '')
        } else {
            fileKey = file?.replace(`addon.`, '')
            file = file?.replace(`addon.${route}.`, '')
        }
        return { file, fileKey, route }
    }
}

export default Language
